package cn.net.greenet.policybank.servlet;

import cn.net.greenet.common.policy_service.PolicySupport;
import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Policyrepositoryinstance;
import cn.net.greenet.db.bean.Policyrepositorytype;
import cn.net.greenet.user.operation.UserPolicyBankAction;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ambimmort.prserver.repository.webservice.InstanceBean;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author Administrator
 */
@WebServlet(name = "cn.net.greenet.policybank.servlet.Create", urlPatterns = {"/policy/create_strategy_instance"})
public class Create extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String type = request.getParameter("type"); //创建策略仓库类型名称
        String instance = request.getParameter("instance");  //创建策略仓库实例名称
        HttpSession hsession = request.getSession(false);
        String username = null;
        try {
            username = hsession.getAttribute("name").toString();
        } catch (Exception e) {
            response.sendRedirect("/WebManage/404.html");
        }

        PrintWriter out = response.getWriter();
        //创建一个指定类型的策略仓库实例

        ArrayList<InstanceBean> instanceList = (ArrayList<InstanceBean>) PolicySupport.getInstance().getApi().listRepositories(type);
        Set<String> instancename = new TreeSet<String>();
        for (InstanceBean i : instanceList) {
            instancename.add(i.getInstance());
        }
        if (instancename.contains(instance.trim())) {
            System.out.println("策略类型：" + type + "策略仓库：" + instance + "重复，添加失败");
            out.println("{\"result\":\"false\"}");
        } else {
            PolicySupport.getInstance().getApi().createRepository(type, instance);
            SessionFactory sf = HibernateUtil.getSessionFactory();
            Session session = sf.openSession();
            session.clear();
            Transaction tx = session.beginTransaction();
            try {
                Policyrepositorytype pt = (Policyrepositorytype) session.get(Policyrepositorytype.class, type);
                Policyrepositoryinstance bean = new Policyrepositoryinstance(pt, instance);
                session.saveOrUpdate(bean);
                tx.commit();
                UserPolicyBankAction.createPolicyBank(username, instance, type);  //写入用户创建策略仓库日志
                try {
                    /* TODO output your page here. You may use following sample code. */
                    out.println("{\"result\":\"true\"}");
                } catch (Exception e) {
                    out.println("{\"result\":\"false\"}");
                }

            } catch (Exception e) {
                e.printStackTrace();
                tx.rollback();
                out.println("{\"result\":\"false\"}");
            } finally {
                out.close();
                session.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
